package com.bruce.practice.thread;

/**
 * @author luotuan
 * @Description
 * @create 2020-05-18 22:42
 **/
public class InterruptedTest {
    public static void main(String[] args) {
        try {
            Thread t1 = new MyThread("t1");  // 新建“线程t1”
            System.out.println(t1.getName() + " (" + t1.getState() + ") is new.");

            t1.start();                      // 启动“线程t1”
            System.out.println(t1.getName() + " (" + t1.getState() + ") is started.");

            // 主线程休眠300ms，然后主线程给t1发“中断”指令。
            //thread.sleep(300);
            t1.interrupt();
            System.out.println(t1.getName() + "的中断状态：" + t1.isInterrupted());
            System.out.println(t1.getName() + " (" + t1.getState() + ") is interrupted.");

            // 主线程休眠300ms，然后查看t1的状态。
            Thread.sleep(300);
            System.out.println(t1.getName() + " (" + t1.getState() + ") is interrupted now.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class MyThread extends Thread {
    public MyThread(String name) {
        super(name);
    }

    @Override
    public void run() {

        int i = 0;
        while (!isInterrupted()) {
            try {
                Thread.sleep(100); // 休眠100ms
                System.out.println(Thread.currentThread().getName() + "的中断状态：" + Thread.currentThread().isInterrupted());
                i++;
                System.out.println(Thread.currentThread().getName() + " (" + this.getState() + ") loop " + i);
            } catch (Exception e) {
                System.out.println(Thread.currentThread().getName() + " (" + this.getState() + ") catch InterruptedException.");
                System.out.println(Thread.currentThread().getName() + "的中断状态：" + Thread.currentThread().isInterrupted());
            }
        }
    }
}
